<?php
// +----------------------------------------------------------------------
// |     【DealMain】Model模型类
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class DealMain extends Model{
    use SoftDelete;
    protected $deleteTime = false;
	
	/**
	 * 用户一对一关联
	 */
	public function customer(){
	    return $this->hasOne(CustomerMain::class, 'id', 'cusid')->append(['address2']);
	}
	
	/**
	 * 订单明细一对多关联
	 */
	public function dealinfo(){
	    return $this->hasMany(DealInfo::class, 'id', 'did');
	}
	
    // 获取列表
    public static function getList($where = []){
        $limit = I('get.limit/d');
		$status = I('get.status','');
		$cusid = I('get.cusid','');
		$year=I('get.year','');
		$month=I('get.month','');
		$day=I('get.day','');
		$keyword = I("keyword",'');

        //按品名查找
        if ($number = I("number")) {
           $where[] = ["number", "like", "%" . $number . "%"];
        }
		if($status!=""){
			$where[] = ['status','=',$status];
		}
		if($cusid!=""){
			$where[] = ['cusid','=',$cusid];
		}
		if($year!=""){
			$where[] = ['year','=',$year];
		}
		if($month!="" && $year!=""){
			$where[] = ['month','=',$month];
		}
		if($day!="" && $month!="" && $year!=""){
			$where[] = ['day','=',$day];
		}
		
		if(($year=='' && $month!='') || (($year=='' || $month=='') && $day!='')){
			return ['msg'=>'选择日期格式不正确','code'=>201];
		}

        $list = self::order('create_time','desc');
		if ($keyword != "") {
			$list = $list->hasWhere('customer',function($query) use ($keyword) {
				$query->where([
					['name|company','like',"%" . $keyword . "%"]
				]);
			});
		}

		$list = $list->with('customer')->append(['create_time2'])->where($where)->paginate($limit);
		
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	// 获取列表数据
	public static function listData($where=[],$order="",$n_page=0,$limit=20){
		$data=self::order($order)->where($where)->with(['customer'])->append(['ocreate_time']);
		if($n_page>0){
			$data=$data->page($n_page,$limit);
		}
		$data=$data->select()->toArray();
		
		return $data;
	}
	
	// 获取某个单条记录
	public static function info($id){
		if(!is_array($id)){
			$model=self::find($id)->append(['ocreate_time']);
		}else{
			$model=self::where($id)->find()->append(['ocreate_time']);
		}
		return $model;		
	}
	
	//	生成订单打印数据
	//	订单数据，订单明细数据，报表文件名称，
	public static function dealPrintData($T,$info,$print=[],$name='FabricSales'){
		
		$data=[
		    "method" =>"printreport",
		    "ReportType" =>"gridreport",
		    "ReportName" => $name.'.grf',
		    "ReportVersion" =>"1",
		    "ReportUrl" => get_host()."/static/tool/print/".$name.".grf",
			"PrinterName" => $print['printer_name'],
		    "Preview" => $print['preview'],
		    "token" => md5($T['number']),
		    "taskid" => $T['number'],
			"Control" => [],
			"Field" => [],
			"Parameter"=>[],
			"Data" => $info,
		];

		$print['deal_remark']=str_replace("<b>","",$print['deal_remark']);
		$print['deal_remark']=str_replace("</b>","",$print['deal_remark']);
		$control=[
			'number' 		=> $T['number'],
			'customer' 		=> $T['customer']['company']=='' ? $T['customer']['name'] : $T['customer']['company'],
			'create_time' 	=> date('Y年m月d日',$T['ocreate_time']),
			'qr_tips'		=> $print['deal_qrcode_tips'],
			'qr_type'		=> intval($print['deal_qrcode_type']??0),
			'deal_remark'	=> $print['deal_remark'],
			'title'			=> $print['title']??'',
			'phone'			=> $print['phone']??'',
		];
		
		// 运费以及优惠说明
		$coupon_text = "";
		if($T['freight'] > 0) $coupon_text.='运费：￥'.price_one($T['freight']).' ';
		if($T['reduce'] > 0) $coupon_text.='优惠：-'.$T['reduce'].' KG ';
		if($T['coupon'] > 0 && $T['paytype'] == '公账开票') $coupon_text.='税费：￥'.price_one($T['coupon']).' ';
		if($T['coupon'] > 0 && $T['paytype'] != '公账开票') $coupon_text.='差价：￥'.price_one($T['coupon']).' ';
		if($T['coupon'] < 0) $coupon_text.='优惠：￥'.price_one($T['coupon']).' ';
		
		$parameter=[
			'total_cn' => cny($T['total']),
			'total' => price_one($T['total']),
			'volume' => $T['volume'],
			'count' => $T['count'],
			'coupon_text' => $coupon_text,
		];
		
		if($print['deal_qrcode_content']!='' && $print['deal_qrocde_print']==1){
			// 二维码
			$data['Control'][]=[
				'type' => 'AsBarcode',
				'name' => 'qrcode',
				'value' => $print['deal_qrcode_content'],
				'required' => false,
			];
		}
		
		
		// Control循环替换内容
		foreach($control as $k=>$c){
			$data['Control'][]=[
				'type' =>'AsStaticBox',
				'name' => $k,
				'value' => $c,
				'required' =>false
			];
		};
		
		// Parameter循环替换内容
		foreach($parameter as $k=>$c){
			$data['Parameter'][]=[
				'type' =>'',
				'name' => $k,
				'value' => $c,
				'required' =>false
			];
		};
		
		//	获取所有字段名
		$field=array_keys($info[0]);
		$field=array_merge($field,[
			'colorid',
			'weight1',
			'weight2',
			'weight3',
			'weight4',
			'weight5',
			'weight6',
			'weight7',
			'weight8',
		]);
		//循环替换内容
		foreach($field as $f){
			$data['Field'][]=[
				'type' =>'ftString',
				'name' => $f,
				'size' => 255,
				'required' =>false
			];
		};
		
		// 循环产品
		for($i=0;$i<count($data['Data']);$i++){
			$data['Data'][$i]['name']=$data['Data'][$i]['number'].'#'.$data['Data'][$i]['name'];
			$data['Data'][$i]['colorid']=$data['Data'][$i]['color'].'#'.$data['Data'][$i]['colorname'];
			$data['Data'][$i]['total']=price_one($data['Data'][$i]['total']);
			$data['Data'][$i]['unitprice']=price_one($data['Data'][$i]['unitprice']);
			$data['Data'][$i]['reduce']=$data['Data'][$i]['reduce']>0?'-'.$data['Data'][$i]['reduce']:'';
			$data['Data'][$i]['weight1']=$data['Data'][$i]['weight'][0];
			$data['Data'][$i]['weight2']=$data['Data'][$i]['weight'][1];
			$data['Data'][$i]['weight3']=$data['Data'][$i]['weight'][2];
			$data['Data'][$i]['weight4']=$data['Data'][$i]['weight'][3];
			$data['Data'][$i]['weight5']=$data['Data'][$i]['weight'][4];
			$data['Data'][$i]['weight6']=$data['Data'][$i]['weight'][5];
			$data['Data'][$i]['weight7']=$data['Data'][$i]['weight'][6];
			$data['Data'][$i]['weight8']=$data['Data'][$i]['weight'][7];
		}
		// p($data);
		return $data;
	}
	
	/** 获取器 **/
	
	public function getCreateTime2Attr($value,$data){
		$value=uc_time_ago($data['create_time']);
	    return $value;
	}
	
	public function getOcreateTimeAttr($value,$data){
		$value=$data['create_time'];
	    return $value;
	}
	
}
